package com.tanhua.commons.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import com.tanhua.commons.properties.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class AliyunSmsTemplate {

    @Autowired
    private AliyunSmsProperties smsProperties;

    /**
     * 使用AK&SK初始化账号Client
     */
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(smsProperties.getAccessKeyId())
                .setAccessKeySecret(smsProperties.getAccessKeySecret());
        config.endpoint = smsProperties.getEndpoint();
        return new Client(config);
    }

    /**
     * 发送短信
     */
    public String sendSms(String mobile) {
        int code = RandomUtils.nextInt(100000, 1000000);
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplateCode())
                    .setTemplateParam("{\"code\":"+code+"}");
            //发送短信
            SendSmsResponse sendSmsResponse = createClient().sendSms(sendSmsRequest);
            //短信响应结果
            String responseCode = sendSmsResponse.getBody().getCode();
            if ("OK".equals(responseCode)) {
                log.info("发送短信成功, 手机号：{} 验证码：{}",mobile, code);
                return String.valueOf(code);
            } else {
                log.warn("发送短信失败, 错误码：{}, 错误消息：{}",responseCode, sendSmsResponse.getBody().getMessage());
                return null;
            }
        } catch (Exception e) {
            log.info("发送短信失败", e);
            return null;
        }
    }
}
